<?php

namespace common\queues;

use common\components\fenzhangtong\FenZhangTong;
use common\models\db\LogSendToFzt;
use common\Tools;
use wodrow\yii2wtools\tools\Model;
use yii\base\BaseObject;
use yii\queue\JobInterface;

/**
 * 保存分账通请求日志，异步队列的形式
 */
class LogFengZhangTongSend extends BaseObject implements JobInterface
{
    /**
     * @var FenZhangTong
     */
    public $fzt;
    public $created_by;
    public $forModelClass;
    public $forModelId;

    public static function doLog(FenZhangTong $fzt, $forModelClass = null, $forModelId = null)
    {
        $logJob = new LogFengZhangTongSend();
        $logJob->fzt = $fzt;
        $logJob->forModelClass = $forModelClass;
        $logJob->forModelId = $forModelId;
        \Yii::$app->queue->push($logJob);
    }

    public function execute($queue)
    {
        $fzt = $this->fzt;
        if (!$fzt) {
            throw new \Exception("未配置分账通组件");
        }
        $model = new LogSendToFzt();
        $model->trans_id = $fzt->transId;
        $model->route = $fzt->route;
        $model->route_name = $fzt->getRouteDesc()[$fzt->route];
        $model->version = $fzt->version;
        $model->plat_no = $fzt->platNo;
        $model->plat_cust_no = $fzt->platCustNo;
        $model->rand_key = $fzt->randKey;
        $model->pre_encryption_data = $fzt->preEncryptionData;
        $model->serial_no = $fzt->serialNo;
        $model->technology_message = $fzt->technologyMessage;
        $model->created_by = $model->updated_by = $this->created_by;
        $model->status = $model::STATUS_ACTIVE;
        $model->resp = Tools::toJson($fzt->resp_arr);
        $model->ret_code = $fzt->ret_code;
        $model->ret_msg = $fzt->ret_msg;
        $model->for_model_class = $this->forModelClass;
        $model->for_model_id = $this->forModelId;
        if (!$model->save()) {
            throw new \Exception(Model::getModelError($model));
        }
    }
}